package com.hanthink.framework.web.service;

import jakarta.annotation.Resource;

import com.hanthink.system.mapper.SysUserMapper;
import com.hanthink.system.service.ISysUserService;
import com.hanthink.system.service.manhour.IFactWorkerUsedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.hanthink.common.constant.Constants;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.core.redis.RedisCache;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.exception.user.CaptchaException;
import com.hanthink.common.exception.user.CaptchaExpireException;
import com.hanthink.common.exception.user.UserPasswordNotMatchException;
import com.hanthink.common.utils.MessageUtils;
import com.hanthink.framework.manager.AsyncManager;
import com.hanthink.framework.manager.factory.AsyncFactory;

/**
 * 登录校验方法
 * 
 * @author hanthink
 */
@Component
public class SysLoginService {
	@Autowired
	private TokenService tokenService;

	@Resource
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private ISysUserService sysUserService;
	// 是否允许账户多终端同时登录（true允许 false不允许）
//	@Value("${token.soloLogin}")
//	private boolean soloLogin;

	/**
	 * 登录验证
	 * 
	 * @param username  用户名
	 * @param password  密码
	 * @param code      验证码
	 * @param uuid      唯一标识
	 * @param loginType 登录类型
	 * @return 结果
	 */
	public String login(String username, String password, String code, String uuid, String loginType) {
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);

		if ("0".equals(loginType) && captcha == null) {
			AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
					MessageUtils.message("user.jcaptcha.expire")));
			throw new CaptchaExpireException();
		}
		if (code != null && !code.equalsIgnoreCase(captcha) && code.isEmpty()) {
			AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
					MessageUtils.message("user.jcaptcha.error")));
			throw new CaptchaException();
		}

		// 用户验证
		Authentication authentication = null;
		try {
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				//将用户试错次数记录在数据表中
//				sysUserService.updateerrorstatus(username);

				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
						MessageUtils.message("user.password.not.match")));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me()
						.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
				throw new CustomException(e.getMessage());
			}
		}
		AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS,
				MessageUtils.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();

//		if (!soloLogin) {
//			// 如果用户不允许多终端同时登录，清除缓存信息
//			String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
//			String userKey = redisCache.getCacheObject(userIdKey);
//			if (StringUtils.isNotEmpty(userKey)) {
//				redisCache.deleteObject(userIdKey);
//				redisCache.deleteObject(userKey);
//			}
//		}
		// 生成token
		return tokenService.createToken(loginUser);
	}
}
